<template>
  <ele-modal
    form
    :width="900"
    :model-value="modelValue"
    title="新建出单表"
    @update:modelValue="updateModelValue"
  >
    <ele-page>
      <ele-card class="step-card">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="118px">
          <el-form-item label="车辆信息" prop="vehicle_id">
            <span
              class="blue pointer"
              v-if="form.vehicle_id == 0"
              @click="openVehicle"
              >请选择</span
            >
            <span class="blue pointer" @click="openVehicle" v-else>{{
              selectedVehicle
            }}</span>
          </el-form-item>
          <el-form-item label="利润要求" prop="profit_target">
            <el-input
              v-model="form.profit_target"
              style="width: 150px; margin-right: 8px"
              disabled
            >
              <template #append>元</template>
            </el-input>
            {{ vehicle.reg_date }}注册，{{ vehicle.age }}年车龄
          </el-form-item>
          <el-form-item label="自定利润">
            <el-radio-group v-model="form.custom_profit_flag">
              <el-radio-button :value="1" label="是" />
              <el-radio-button :value="0" label="否" />
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="自定利润"
            prop="custom_profit_target"
            v-if="form.custom_profit_flag == 1"
          >
            <el-input v-model="form.custom_profit_target" style="width: 150px">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="相关材料"
            prop="custom_profit_target_images"
            v-if="customProfit == true"
          >
            <image-upload
              :limit="99"
              v-model="form.custom_profit_target_images"
            />
          </el-form-item>
          <!-- <el-form-item label="报价要求" prop="insurance_remark">
            <el-input
              v-model="form.insurance_remark"
              style="width: 400px"
              type="textarea"
              :rows="3"
              placeholder="不需报价就留空"
            />
          </el-form-item> -->
          <!-- <el-form-item label="商业险报价要求" prop="insurance_b_remark">
            <el-input
              v-model="form.insurance_b_remark"
              style="width: 400px"
              type="textarea"
              :rows="3"
            />
          </el-form-item> -->

          <!-- <el-form-item label="附加险种" prop="other">
            <el-select
              v-model="form.other"
              multiple
              placeholder="请选择"
              style="width: 400px"
            >
              <el-option label="超赔险" value="超赔险" />
              <el-option label="货运险" value="货运险" />
              <el-option label="安责险" value="安责险" />
              <el-option label="承运险" value="承运险" />
              <el-option label="驾意险" value="驾意险" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="管理费" prop="glf_price">
            <el-input v-model="form.glf_price" style="width: 150px">
              <template #prepend>应收</template>
              <template #append>元</template>
            </el-input>
            <el-input
              v-model="form.glf_note"
              style="width: 300px"
              class="ml8"
              placeholder="不收请说明原因"
            />
          </el-form-item>
          <el-form-item label="GPS费" prop="gps_price">
            <el-input v-model="form.gps_price" style="width: 150px">
              <template #prepend>应收</template>
              <template #append>元</template>
            </el-input>
            <el-input
              v-model="form.gps_note"
              style="width: 300px"
              class="ml8"
              placeholder="不收请说明原因"
            />
          </el-form-item>
          <el-form-item label="二保费" prop="eb_price">
            <el-input v-model="form.eb_price" style="width: 150px">
              <template #prepend>应收</template>
              <template #append>元</template>
            </el-input>
            <el-input
              v-model="form.eb_note"
              style="width: 300px"
              class="ml8"
              placeholder="不收请说明原因"
            />
          </el-form-item>
          <el-form-item label="学习费" prop="xx_price">
            <el-input v-model="form.xx_price" style="width: 150px">
              <template #prepend>应收</template>
              <template #append>元</template>
            </el-input>
            <!-- <el-input v-model="form.xx_paid" style="width: 150px" class="ml8">
              <template #prepend>实收</template>
              <template #append>元</template>
            </el-input> -->
          </el-form-item>
          <el-form-item label="盖章费" prop="gz_price">
            <el-input v-model="form.gz_price" style="width: 150px">
              <template #prepend>应收</template>
              <template #append>元</template>
            </el-input>
            <!-- <el-input v-model="form.gz_paid" style="width: 150px" class="ml8">
              <template #prepend>实收</template>
              <template #append>元</template>
            </el-input> -->
          </el-form-item>
          <el-form-item label="法务费" prop="fw_price">
            <el-input v-model="form.fw_price" style="width: 150px">
              <template #prepend>应收</template>
              <template #append>元</template>
            </el-input>
            <!-- <el-input v-model="form.fw_paid" style="width: 150px" class="ml8">
              <template #prepend>实收</template>
              <template #append>元</template>
            </el-input> -->
          </el-form-item>
          <el-form-item label="其他费用">
            <div
              v-for="(item, index) in qtList"
              :key="item.id"
              style="margin-bottom: 8px"
            >
              <el-input v-model="item.title" style="width: 200px">
                <template #prepend>费用名</template>
              </el-input>
              <el-input v-model="item.price" style="width: 120px" class="ml8">
                <template #append>元</template>
              </el-input>
              <span
                class="blue pointer ml8"
                v-if="index != 0"
                @click="delItem(index)"
              >
                删
              </span>
              <span class="blue pointer ml8" v-if="index == 0" @click="addItem">
                添加
              </span>
            </div>
          </el-form-item>
          <el-form-item label="备注说明" prop="remark">
            <el-input
              v-model="form.remark"
              style="width: 400px"
              type="textarea"
              :rows="3"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="loading" @click="save">
              保存
            </el-button>
          </el-form-item>
        </el-form>
      </ele-card>

      <Vehicle v-model="showVehicle" @done="chooseDone" />
    </ele-page>
  </ele-modal>
</template>

<script setup>
  import { ref, reactive, watch } from 'vue';
  import { updateTrade } from '@/api/company';
  import { ElMessage } from 'element-plus';
  import Vehicle from './choose-vehicle.vue';
  import { EleMessage } from 'ele-admin-plus/es';
  import ImageUpload from '@/components/ImageUpload/index.vue';
  import { useFormData } from '@/utils/use-form-data';

  const emit = defineEmits(['done', 'update:modelValue']);
  /** 更新modelValue */
  const updateModelValue = (value) => {
    emit('update:modelValue', value);
  };

  const props = defineProps({
    /** 弹窗是否打开 */
    modelValue: Boolean,
    /** 修改回显的数据 */
    data: Object,
    vehicleId: {
      type: Number,
      default: 0
    },
    plateNumber: String
  });

  const title = ref('');
  const customProfit = ref(false);

  const qtList = ref([
    {
      title: '',
      price: ''
    }
  ]);

  const addItem = () => {
    qtList.value.push({
      title: '',
      price: ''
    });
  };

  const delItem = (i) => {
    qtList.value.splice(i, 1);
  };

  /** 选择车辆 */
  const showVehicle = ref(false);
  const openVehicle = () => {
    showVehicle.value = true;
  };

  /** 提交状态 */
  const loading = ref(false);

  /** 表单实例 */
  const formRef = ref(null);

  /** 表单数据 */
  const [form, resetFields] = useFormData({
    vehicle_id: 0,
    plate_number: '',
    company: '',
    insurance_remark: '',
    glf_price: '', // 管理费
    glf_note: '', // 管理费
    gps_price: '', // gps
    gps_note: '', // gps
    eb_price: '', // 二保
    eb_note: '', // 二保
    xx_price: '', // 学习
    gz_price: '', // 盖章
    fw_price: '', // 法务
    qt_price: '', // 其他
    custom_profit_target: '',
    custom_profit_target_images: '',
    profit_target: '',
    custom_profit_flag: 0,
    remark: ''
  });

  const validateNumber = (rule, value, callback) => {
    if (!value) {
      return callback(new Error('请选择车辆'));
    } else if (isNaN(value)) {
      return callback(new Error('请选择车辆'));
    } else if (value <= 0) {
      return callback(new Error('请选择车辆'));
    } else {
      callback();
    }
  };

  const rules = reactive({
    vehicle_id: [{ validator: validateNumber, trigger: 'blur' }]
  });

  /** 提交 */
  const save = () => {
    if (!validateFees()) return;
    formRef.value?.validate?.((valid) => {
      if (!valid) {
        return;
      }
      var requestData = Object.assign({}, form);
      requestData.qtList = JSON.stringify(qtList.value);
      if (customProfit.value == false) {
        requestData.custom_profit_target = 0;
        requestData.custom_profit_target_images = '';
      }
      updateTrade(requestData)
        .then(() => {
          loading.value = false;
          EleMessage.success('操作成功');
          updateModelValue(false);
          emit('done');
        })
        .catch((e) => {
          loading.value = false;
          console.log(e);
        });
    });
  };

  const validateFees = () => {
    const { glf_price, glf_note, gps_price, gps_note, eb_price, eb_note } =
      form;

    const isEmpty = (val) =>
      val === '' ||
      val === null ||
      val === undefined ||
      val === 0 ||
      val === '0' ||
      val === '0.00';

    if (isEmpty(glf_price) && !glf_note) {
      ElMessage.error('管理费未交，必须填写管理费说明');
      return false;
    }
    if (isEmpty(gps_price) && !gps_note) {
      ElMessage.error('GPS费未交，必须填写GPS费说明');
      return false;
    }
    if (isEmpty(eb_price) && !eb_note) {
      ElMessage.error('二保费未交，必须填写二保费说明');
      return false;
    }

    return true;
  };

  /** 选择完车辆 */
  const selectedVehicle = ref('');
  const vehicle = ref([]);
  const chooseDone = (e) => {
    console.log(e, '????');
    showVehicle.value = false;
    form.vehicle_id = e.id;
    form.company = e.company;
    form.plate_number = e.plate_number;
    form.profit_target = e.profitTarget;
    selectedVehicle.value = e.plate_number + ' - ' + e.company;
    vehicle.value = e;
  };

  watch(
    () => props.modelValue,
    (modelValue) => {
      if (modelValue) {
        title.value = props.plateNumber + '的出单通知';
        vehicle.value = [];
        if (props.data) {
          form.vehicle_id = props.data.id;
          form.company = props.data.company;
          form.plate_number = props.data.plate_number;
          form.profit_target = props.data.profitTarget;
          vehicle.value = props.data;
          selectedVehicle.value =
            props.data.plate_number + ' - ' + props.data.company;
        }
        customProfit.value = false;
        qtList.value = [
          {
            title: '',
            price: ''
          }
        ];
      } else {
        console.log('关闭');
        resetFields();
        formRef.value?.clearValidate?.();
      }
    }
  );
</script>
